#!/usr/bin/python

import pyotp
import sys,os
import re
import hashlib
import sqlite3

def DB_Check(User, Pass):

    db =sqlite3.connect('/etc/openvpn/auth/openvpn.db')

    try:
        cursor = db.cursor()
        cursor.execute("SELECT salt FROM user WHERE username = '%s' and password = '%s' " %(User, Pass))
        data = cursor.fetchone()
    except:
        return False, 2

    if not data :
        return False, 1

    salt = data[0]
    if not salt:
        return False, 1

    return salt, 0

def Goog_Check(Salt, Code):

    totp = pyotp.TOTP(Salt)
    if totp.now() != Code:
        return False, 1
    
    return True, 0

def Read_File(oFile):
    rErun_NP = []

    try:
        oFile_NP = open(oFile, 'r')
        for line in oFile_NP:
            rErun_NP.append(line.strip('\n'))
    except:
        return 1, 1, 1, 1
    else:
        oFile_NP.close()

    try:
        User = rErun_NP[0]
        Pass = re.findall(r"\S+(?=[0-9]{6}$)",rErun_NP[1])[0]
        #Pass = rErun_NP[1][0:-6]
        Pass = hashlib.md5(Pass.encode('utf8')).hexdigest()
        Code = re.findall(r"[0-9]{6}$",rErun_NP[1])[0]
        #Code=rErun_NP[1][-6:]
    except:
        return 2, 2, 2, 2

    return User, Pass, Code, 0

if __name__ == '__main__':

    User, Pass, Code, Err = Read_File(sys.argv[1])
    if Err != 0:
        print("file failed")
        sys.exit(1)

    print(User)
    print(Pass)
    print(Code)

    Salt, Err = DB_Check(User, Pass)
    if Err != 0:
        print("db authentication failed")
        sys.exit(1)

    Ok, Err = Goog_Check(Salt,Code)
    if Err != 0:
        print("google authentication failed")
        sys.exit(1)

